<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <title>4.5 幻灯片的操控部分--滑动切换</title>
    <link rel="stylesheet" href="css/slider.css">
</head>
<body>
    <div id="slider" class="slider">
        <div class="slider-item-container">
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/1.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/2.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/3.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/4.jpg" alt="slider" class="slider-img">
                </a>
            </div>
            <div class="slider-item">
                <a href="###" class="slider-link">
                    <img src="img/5.jpg" alt="slider" class="slider-img">
                </a>
            </div>
        </div>
    </div>

    <script src="js/hammer.min.js"></script>
    <script src="js/slider.js"></script>
    <script>
        var slider = new Slider(document.getElementById('slider'), {
            initIndex: 0, // 初始显示第几张幻灯片，从0开始
            speed: 300, // 幻灯片的切换速度
            hasIndicator: true // 是否需要指示器indicator
        });

        var hammer = new Hammer(slider.getItemContainer());

        var isSwiping = false;

        hammer.on('panmove', function (ev) {
            var distance = ev.deltaX + slider.getDistanceByIndex(slider.getIndex());

            slider.move(distance);
        });
        hammer.on('panend', function (ev) {
            if (isSwiping) return;

            var distance = ev.deltaX + slider.getDistanceByIndex(slider.getIndex());
            var index = getIndexByDistance(distance);

            slider.to(index);
        });

        // 根据容器移动的距离获取索引
        function getIndexByDistance(distance) {
            if (distance > 0) {
                return 0;
            } else {
                return Math.round(-distance / slider.getDistancePerSlide());
            }
        }

        hammer.on('swipeleft', function (ev) { // next
            isSwiping = true;
            slider.next(function () {
                isSwiping = false;
            });
        });
        hammer.on('swiperight', function (ev) { // prev
            isSwiping = true;
            slider.prev(function () {
                isSwiping = false;
            });
        });
    </script>
</body>
</html>